<template>
  <!-- 海报弹框 -->
  <view>
    <uni-popup ref="tipsPopup" type="bottom">
      <view class="container">
        <!-- 隐藏的Canvas -->
        <canvas
          canvas-id="myCanvas"
          :style="{
            width: canvasWidth + 'px',
            height: canvasHeight + 'px',
            position: 'fixed',
            left: '-9999px',
          }"
        ></canvas>

        <!-- 预览生成的图片 -->
        <view class="posterList">
          <image
            v-if="finalImagePath"
            :src="finalImagePath"
            mode="widthFix"
            style="width: 290px; height: 543px"
            class="preview-image"
          ></image>

          <!-- 操作按钮 -->
          <!-- <button @click="generateImage">生成图片</button> -->
          <button
            @click="saveToAlbum"
            v-if="finalImagePath"
            class="btn posAb-left-50"
          >
            保存到本地相册
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
// import { getPoster } from "@/api/user";
import { mapGetters } from "vuex";
import { mpQrcode } from "@/api/api";
export default {
  computed: mapGetters(["isLogin"]),
  data() {
    return {
      canvasWidth: 533, // Canvas宽度
      canvasHeight: 947, // Canvas高度（根据背景图比例调整）
      ossImageUrl:
        "https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/placard.png", // OSS背景图
      qrCodeBase64: "", // Base64二维码
      finalImagePath: "", // 最终生成的图片路径
    };
  },
  mounted() {
    // this.getData();
  },
  methods: {
    async getData() {
      uni.showLoading({
        title: "加载中...",
      });
      let that = this;
      if (this.$store.state.app.userInfo.icode) {
        let str = that.$store.state.app.userInfo;
        let icode = "";
        if (str.icode.indexOf("TY") != -1) {
          icode = str.icode.slice(0, -2);
        } else {
          icode = str.icode;
        }
        let scene = `sd=${that.$store.state.app.uid}&icode=${icode}`;
        let data = {
          is_hyaline: true,
          width: 400,
          auto_color: false,
          page: "pages/index/index",
          scene,
          line_color: { r: "0", g: "0", b: "0" },
        };
        mpQrcode(data).then((res) => {
          this.getQrCode(res.data.code);
          setTimeout(() => {
            this.generateImage();
          }, 1000);
          // this.qrCodeBase64 = await this.base64ToTempPath(res.data.code);
        });
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "没有获取到个人邀请码、请先登录",
          icon: "none",
        });
      }
    },
    open() {
      this.$refs.tipsPopup.open();
    },
    // 取消登录弹框
    cancel() {
      this.$refs.tipsPopup.close();
    },
    // 将 Base64 转为临时文件路径（微信小程序）
    base64ToTempPath(base64) {
      return new Promise((resolve, reject) => {
        const fs = wx.getFileSystemManager();
        const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;
        // 去掉 Base64 前缀（如 "data:image/png;base64,"）
        const base64Data = base64.split(",")[1] || base64;
        fs.writeFile({
          filePath,
          data: base64Data,
          encoding: "base64",
          success: () => resolve(filePath),
          fail: (err) => {
            reject(err);
          },
        });
      });
    },
    async getQrCode(code) {
      this.qrCodeBase64 = await this.base64ToTempPath(code);
      // console.log("111111111111111", this.qrCodeBase64);
    },
    // 生成图片（背景 + 二维码）
    async generateImage() {
      const ctx = uni.createCanvasContext("myCanvas", this);
      // 1. 下载OSS背景图（仍需网络下载）
      const bgPath = await this.downloadImage(this.ossImageUrl);
      if (!bgPath) return;
      // 2. 绘制背景图
      ctx.drawImage(bgPath, 0, 0, this.canvasWidth, this.canvasHeight);
      // 3. 直接绘制Base64二维码
      const qrSize = 275;
      const qrX = (this.canvasWidth - qrSize) / 2;
      const qrY = this.canvasHeight - qrSize - 275;
      ctx.drawImage(this.qrCodeBase64, qrX, qrY, qrSize, qrSize); // 关键点：直接使用Base64
      // 4. 可选：上部分添加文字
      ctx.font = "font-style font-weight font-size font-family";
      ctx.setFontSize(20);
      ctx.setFillStyle("#000000");
      // ctx.setFontWeight("bold");
      ctx.fillText("扫描二维码", qrX + 90, this.canvasHeight - 230);
      // 4. 可选：下部分添加文字
      ctx.setFontSize(20);
      ctx.setFillStyle("#000000");
      ctx.fillText("获取更多收益", qrX + 80, this.canvasHeight - 200);
      ctx.setFontSize(30);
      ctx.setFillStyle("#000000");
      let nickname = this.$store.state.app.userInfo.nikeName
        ? this.$store.state.app.userInfo.nikeName.length > 12
          ? this.$store.state.app.userInfo.nikeName.substring(0, 12)
          : this.$store.state.app.userInfo.nikeName
        : "";
      // 绘画用户名称
      ctx.fillText(nickname, qrX + 62, this.canvasHeight - 70);
      // 绘画用户头像
      let avatar = "";
      if (!avatar.includes("http") && avatar.includes("https")) {
        avatar =
          "https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/standbyNotLogged.png";
      } else {
        avatar = this.$store.state.app.userInfo.avatar;
      }
      const headPath = await this.downloadImage(avatar);
      if (!headPath) return;
      // ctx.save(); // 保存当前绘图状态
      // ctx.beginPath();
      // ctx.drawImage(headPath, qrX - 100, this.canvasHeight - 100, 90, 90);
      ctx.save(); // 保存当前绘图状态

      // 1. 绘制圆形图片
      ctx.beginPath();
      const centerX = qrX - 55 + 45; // 圆心X坐标
      const centerY = this.canvasHeight - 130 + 45; // 圆心Y坐标
      const radius = 45; // 半径
      ctx.arc(centerX, centerY, radius - 2, 0, Math.PI * 2); // 半径减2留出边框空间
      ctx.closePath();
      ctx.clip(); // 设置圆形裁剪区域
      ctx.drawImage(headPath, qrX - 55, this.canvasHeight - 130, 90, 90); // 绘制图片

      // 2. 绘制白色边框
      ctx.restore(); // 恢复绘图状态（解除clip）
      ctx.save(); // 再次保存状态
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, Math.PI * 2); // 使用完整半径绘制边框
      ctx.lineWidth = 4;
      ctx.strokeStyle = "#FFFFFF";
      ctx.stroke();
      ctx.restore(); // 恢复状态
      // 5. 生成图片
      ctx.draw(false, () => {
        setTimeout(() => {
          this.canvasToTempFile();
        }, 300);
      });
    },

    // 下载OSS图片（仅背景图需要）
    downloadImage(url) {
      try {
        return new Promise((resolve) => {
          uni.downloadFile({
            url,
            success: (res) => {
              if (res.statusCode === 200) {
                resolve(res.tempFilePath);
              } else {
                uni.showToast({ title: "背景图下载失败", icon: "none" });
                resolve(null);
              }
            },
            fail: (err) => {
              console.error("下载失败:", err);
              resolve(null);
            },
          });
        });
      } catch (err) {
        console.error("失败原因:", err);
      }
    },

    // Canvas转图片文件
    canvasToTempFile() {
      uni.canvasToTempFilePath(
        {
          canvasId: "myCanvas",
          success: (res) => {
            this.finalImagePath = res.tempFilePath;
            uni.hideLoading();
            // uni.showToast({ title: "生成成功", icon: "success" });
          },
          fail: (err) => {
            console.error("生成图片失败:", err);
            uni.hideLoading();
          },
        },
        this
      );
    },

    // 保存到相册
    saveToAlbum() {
      uni.saveImageToPhotosAlbum({
        filePath: this.finalImagePath,
        success: () => {
          uni.showToast({ title: "保存成功", icon: "success" });
        },
        fail: (err) => {
          if (err.errMsg.includes("auth deny")) {
            uni.showModal({
              title: "提示",
              content: "需要相册权限才能保存",
              success: (res) => {
                if (res.confirm) uni.openSetting();
              },
            });
          }
        },
      });
    },
  },
};
</script>

<style>
.container {
  height: 80vh;
  position: relative;
  /* padding: 20px;
  text-align: center; */
}
.preview-image {
  /* width: 100%;
  margin: 20px 0; */
  /* border: 1px solid #eee; */
}
.posterList {
  position: absolute;
  top: 6%;
  left: 50%;
  transform: translate(-50%, -6%);
}
.btn {
  width: 384rpx;
  height: 98rpx;
  background: #ff9c89;
  border-radius: 49rpx;
  font-size: 31rpx;
  color: #ffffff;
  text-align: center;
  line-height: 98rpx;
  margin-top: 30rpx;
}
</style>
